﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using Ue.Core;
using Ue.Utility;

namespace Ue.Components.VerificationCode
{
    public class VerifyImageDrawContext
    {
        public LazyField<Graphics> lazyGraphics;
        public VerifyImageDrawContext() : this(new Bitmap(130,53)) { }
        public VerifyImageDrawContext(Bitmap bitmap)
        {
            //this.CoordinateOfDraw = new Coordinate();

            this.Bitmap = bitmap;
            this.lazyGraphics = new LazyField<Graphics>(() =>
            {
                var graphics = System.Drawing.Graphics.FromImage(this.Bitmap);
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

                return graphics;
            });
        }

        public Bitmap Bitmap { get; set; }

        public Graphics Graphics
        {
            get { return this.lazyGraphics.Value; }
        }

        //public Font Font { get; set; }

        //public Color Color { get; set; }

        /// <summary>
        /// 当前坐标
        /// </summary>
        //public Coordinate CoordinateOfDraw { get; private set; }

        public VerifyImage Save()
        {
            var verifyImage = new VerifyImage();

            using (MemoryStream stream = new MemoryStream())
            {
                ImageCodecInfo imageCodecInfo = ImageHelper.GetImageDecoder(".png");
                if (imageCodecInfo != null)
                {
                    this.Bitmap.Save(stream, imageCodecInfo, ImageHelper.GetQualityEncoderParameters(100));
                }
                else
                {
                    this.Bitmap.Save(stream, ImageFormat.Jpeg);
                }

                verifyImage.ContentType = imageCodecInfo.MimeType;
                verifyImage.VerifyData = stream.ToArray();
            }

            this.Graphics.Dispose();
            this.Bitmap.Dispose();

            return verifyImage;
        }

        public class Coordinate
        {
            public float X { get; set; }

            public float Y { get; set; }
        }
    }
}
